package top.dbpanda.cmsjpa.learn.thread.juc;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author 20018954
 */
public class TestReadWriteLock {
    /**
     * 读写锁
     */
    private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

    public static void main(String[] args) {
        TestReadWriteLock testReadWriteLock = new TestReadWriteLock();
        new Thread(() -> {
            //读操作
            testReadWriteLock.myRead(Thread.currentThread());
            //写操作
            testReadWriteLock.myWrite(Thread.currentThread());
        }, "t1").start();
        new Thread(() -> {
            //读操作
            testReadWriteLock.myRead(Thread.currentThread());
            //写操作
            testReadWriteLock.myWrite(Thread.currentThread());
        }, "t2").start();
    }

    private void myWrite(Thread currentThread) {
        rwl.writeLock().lock();
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println(currentThread.getName() + "正在进行写操作");
            }
            System.out.println(currentThread.getName() + "===写操作完毕====");
        } finally {
            rwl.writeLock().unlock();
        }
    }

    private void myRead(Thread currentThread) {
        rwl.readLock().lock();
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println(currentThread.getName() + "正在进行读操作");
            }
            System.out.println(currentThread.getName() + "===读操作完毕====");
        } finally {
            rwl.readLock().unlock();
        }
    }
}
